package com.gree.pool.file;

import java.io.*;
import com.gree.entity.TrsT001FiDocumentHeader;
import com.gree.entity.TrsT003ServiceRequest;
import com.gree.entity.TrsT021RunmoveRecord;
import com.gree.entity.TrsT022LoggerRecord;
import com.gree.service.ITrsT001FiDocumentHeaderService;
import com.gree.service.ITrsT003ServiceRequestService;
import com.gree.service.ITrsT021RunmoveRecordService;
import com.gree.service.ITrsT022LoggerRecordService;
import com.gree.utils.Files;
import com.gree.utils.MessageID;
import com.gree.utils.SpringBeanFactoryUtils;
import com.gree.utils.UniqueIDTool;

public class ReadFile implements Runnable {
	private static final String encoding = "UTF-8";
	 
	private String path;
	private String loginId;
	private String userId;
	private String infoId;
	private String companyId;
	private String fileName;
	private Integer rowLines;

	public ReadFile(String path, String loginId, String userId, String infoId,String companyId, String fileName, Integer rowLines) {
		super();
		this.path = path;
		this.loginId = loginId;
		this.userId = userId;
		this.infoId = infoId;
		this.companyId = companyId;
		this.fileName = fileName;
		this.rowLines = rowLines;
	}

	@Override
	public void run() {
		File fi = null;
		ITrsT021RunmoveRecordService ckps = null;
		Integer sum = 0;
		String SRV_REQ_NO = "";
		
		try {
			ITrsT001FiDocumentHeaderService headerService = (ITrsT001FiDocumentHeaderService) SpringBeanFactoryUtils.getBean("headerService");// 抬头
			ITrsT003ServiceRequestService requestService = (ITrsT003ServiceRequestService) SpringBeanFactoryUtils.getBean("requestService");// 服务请求
		    ckps = (ITrsT021RunmoveRecordService) SpringBeanFactoryUtils.getBean("recordService");// 运行记录
			ITrsT022LoggerRecordService logerService = (ITrsT022LoggerRecordService) SpringBeanFactoryUtils.getBean("loggerRecordService");// 详细记录
			TrsT021RunmoveRecord obsj = new TrsT021RunmoveRecord();
		
			obsj.setInfoId(infoId);
			obsj.setLockFlag("R");// 运行状态
			obsj.setMessage("正在运行中"); // 更新消息
			obsj.setFileName(fileName);
		    obsj.setCompanyId(companyId);
			obsj.setHoldUser(userId);
			obsj.setLoginId(loginId);
			ckps.editorRunDateRecord(obsj);
			
			fi = new File(path);
			if (fi.exists() && fi.length() <= 2339) {

				String message = MessageID.FILE_DOES_NOT.replace("#FILE_NAME#",fi.getName());
			 
				TrsT021RunmoveRecord os = new TrsT021RunmoveRecord();
				os.setInfoId(infoId);
				os.setFileName(fi.getName());
				os.setCompanyId(companyId);
				os.setHoldUser(userId);
				os.setLoginId(loginId);
				os.setLockFlag("N");// 运行状态
				os.setMessage(message); // 更新消息
				ckps.editorEndDateRecord(os);
				Files.writeByFileWriter(fi.getParent() , fi.getName(), message);
		 
				
				return;
			} else {
				Files.writeByFileWriter(fi.getParent(), fi.getName(),MessageID.READ_FILE_START.replace("#FILE_NAME#",fi.getName()));
				FileInputStream in = new FileInputStream(fi);
				InputStreamReader read = new InputStreamReader(in, encoding);
				BufferedReader buffer = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = buffer.readLine()) != null) {
					long starTime = System.currentTimeMillis();
					sum = sum + 1;
					if (lineTxt.equals("")) {
						continue;
					}
					
					if (sum >=rowLines) {
						Files.writeByFileWriter(fi.getParent() ,fi.getName(),Files.formats(sum, "读取行内容", starTime));
						lineTxt = lineTxt + "#";
						String[] arrs = lineTxt.split("\t");
						String string = arrs[arrs.length - 1];
						arrs[arrs.length - 1] = string.substring(0,string.lastIndexOf("#"));
						String DOCUMENT_NO = arrs[3];// 会计凭证编号
						String FIN_YEAR = arrs[2];// 年
						String FIN_PERIOD = arrs[6];// 月
					
						if (arrs[11].length() >= 10) {
							SRV_REQ_NO = (arrs[11].substring(0, 10)).replaceAll("\\s*", "");
							String message = MessageID.SLIP_BKTXT_SUCCESS.replace("#BKTXT#", arrs[11])+ SRV_REQ_NO+ "】";
							Files.writeByFileWriter(fi.getParent(),fi.getName(),message);
							Files.writeByFileWriter(fi.getParent() , fi.getName(),Files.formats(sum, "分割并取得服务请求编号", starTime));
						} else {
							String message = MessageID.SLIP_BKTXT_ERROR.replace("#BKTXT#", arrs[11]);
							Files.writeByFileWriter(fi.getParent(),fi.getName(),message);
							continue;
						}
						String AWTYP = arrs[32];
						String AWKEY = arrs[33];

						String REV_DOCUMENT_NO = arrs[25];
						String REV_YEAR = arrs[26];
						if (REV_YEAR.equals("0000")) {
							REV_YEAR="";
						}
						if (REV_DOCUMENT_NO.length()==0) {
							REV_DOCUMENT_NO="";
							Files.writeByFileWriter(fi.getParent(),fi.getName(), "冲销凭证号【"+REV_DOCUMENT_NO+"】为空");
						}
						TrsT003ServiceRequest objs=new TrsT003ServiceRequest();
						objs.setSrvReqNo(SRV_REQ_NO);
						objs.setRevDocumentNo(REV_DOCUMENT_NO);
						TrsT003ServiceRequest docInfo = requestService.getRequestBysrvReqStatus(objs);
 						Files.writeByFileWriter(fi.getParent(),fi.getName(), "冲销凭证号："+REV_DOCUMENT_NO);
 						if (docInfo == null) {
 							String message = MessageID.SRV_REQ_NOT_EXIST.replace("#SRV_REQ_NO#", SRV_REQ_NO);
							Files.writeByFileWriter(fi.getParent(),fi.getName(), message);
						 
 						}else{
 							String categoryID = docInfo.getCategoryId3();
							String docStatus = docInfo.getStatus();
							if (categoryID.contains("_CP_010_020")) {
								Files.writeByFileWriter(fi.getParent(), fi.getName(),"判断当前服务请求编号【 " + SRV_REQ_NO+ "】的业务类型是否是" + companyId+ "_CP_010_020");
								docStatus = "ST_DOC_STATUS_POST01";
								String message="判断当前服务请求编号【 " + SRV_REQ_NO+ "】的业务类型是支付中转换,则修改凭证抬头状态为：ST_DOC_STATUS_POST01，服务请求状态为：ST_COMMON_0000000010";
								Files.writeByFileWriter(fi.getParent(), fi.getName(),message);
							}
							Files.writeByFileWriter(fi.getParent(), fi.getName(),Files.formats(sum, "更新会计凭证编号", starTime));
							TrsT001FiDocumentHeader headers = new TrsT001FiDocumentHeader();
							headers.setDocumentNo(DOCUMENT_NO);
							headers.setSrvReqNo(SRV_REQ_NO);
							headers.setFinYear(FIN_YEAR);// 年
							headers.setFinPeriod(FIN_PERIOD);// 月
							headers.setStatus(docStatus);
							headers.setAwtyp(AWTYP);
							headers.setAwkey(AWKEY);
							headers.setRevYear(REV_YEAR);
							headers.setRevDocumentNo(REV_DOCUMENT_NO);
							headers.setInfoIdDoc(docInfo.getInfoIdDoc());
							Integer ints = headerService.updateDocumentHeaderById(headers);
							if (ints == 0) {
								String message = MessageID.DOCUMENT_NO_UPDATE.replace("#DOCUMENT_NO#",DOCUMENT_NO);
								Files.writeByFileWriter(fi.getParent(),fi.getName(),message);
							} else {
								String message = MessageID.DOCUMENT_NO_SUCCESS.replace("#DOCUMENT_NO#",DOCUMENT_NO);
								Files.writeByFileWriter(fi.getParent(), fi.getName(),Files.formats(sum, "保存详细记录", starTime));
															
								TrsT022LoggerRecord loger = new TrsT022LoggerRecord();
								loger.setInfoId(UniqueIDTool.getUniqueID()); // 主键
								loger.setCompanyId(companyId); // 公司代码
								loger.setDocumentNo(DOCUMENT_NO); // 凭证编号
								loger.setSrvReqNo(SRV_REQ_NO); // 请求编号
								loger.setHoldUser(userId); // 操作对象
								loger.setLockFlag("S"); // 操作状态
								loger.setFileName(fi.getName()); // 文件名称
								loger.setMessage(message); // 更新消息
								logerService.insertLoggerRecord(loger);
								
								TrsT021RunmoveRecord obs = new TrsT021RunmoveRecord();
								obs.setInfoId(infoId);
								obs.setFileName(fi.getName());
								obs.setCompanyId(companyId);
								obs.setLoginId(loginId);
								obs.setRowLines(Double.valueOf(String.valueOf(sum)));
								ckps.editorRowLines(obs);
								TrsT003ServiceRequest obj=new TrsT003ServiceRequest();
								obj.setSrvReqNo(SRV_REQ_NO);
								obj.setCategoryId3(companyId+"_CP_010_020");
							    obj.setSrvReqStatus("ST_COMMON_0000000010");
								requestService.updateNonEmptyServicetById(obj);
								Files.writeByFileWriter(fi.getParent(),fi.getName(), message);	

							}
 						}
					}
					Files.writeByFileWriter(fi.getParent() , fi.getName(),Files.geSum(sum, starTime));
				}
				buffer.close();
				read.close();
				in.close();
				TrsT021RunmoveRecord objt = new TrsT021RunmoveRecord();
				objt.setInfoId(infoId);
				objt.setLockFlag("S");// 运行状态
				objt.setMessage("更新成功"); // 更新消息
				objt.setFileName(fi.getName());
				objt.setCompanyId(companyId);
				objt.setLoginId(loginId);
				objt.setRowLines(Double.valueOf(String.valueOf(sum)));
				ckps.editorEndDateRecord(objt);
				String message = MessageID.READ_SUCCESS_FILE.replace("#FILE_NAME#", fi.getName());
				Files.writeByFileWriter(fi.getParent(),fi.getName(),message);
			} 
		} catch (Exception e) {
			TrsT021RunmoveRecord objt = new TrsT021RunmoveRecord();
			objt.setInfoId(infoId);
			objt.setLockFlag("T");// 运行状态
			objt.setMessage("更新失败"+" 第【"+sum+"】行的服务请求号【"+SRV_REQ_NO+"】 "+e.getMessage()); // 更新消息
			objt.setFileName(fileName);
			objt.setCompanyId(companyId);
			objt.setLoginId(loginId);
			objt.setRowLines(Double.valueOf(String.valueOf(sum)));
			ckps.editorEndDateRecord(objt);
			Files.writeByFileWriter(fi.getParent(),fi.getName(),e.getMessage());

		}
	}
}
